<!-- 人工智能 -->
<template>
  <div class="dashboard-editor-container">
    <el-row style="background: #fff">
      <div class="container" style="display: flex">
        <div class="lefttree" style="height: calc(100vh - 86px); overflow: hidden">
          <el-tree node-key="ID" :data="CustomerList" :expand-on-click-node="false" :props="defaultProps"
            @node-click="handleNodeClick" default-expand-all highlight-current style="width: 200px">
            <span slot-scope="{ node }" class="custom-tree-node">
              <!-- data -->
              <span>
                <svg-icon v-show="node.level === 1" icon-class="peoples" style="margin-right: 10px" />
                <svg-icon v-show="node.level === 2" icon-class="user" style="margin-right: 10px" />
                <i v-show="node.label === '信息咨询'" class="el-icon-chat-dot-round" style="margin-right: 10px" />
                <i v-show="node.label === '文案撰写'" class="el-icon-edit-outline" style="margin-right: 10px" />
                <i v-show="node.label === '图片创造'" class="el-icon-picture-outline" style="margin-right: 10px" />
                <span class="tree-text">{{ `${node.label}` }}<span v-show="node.level > 2">（{{ node.data.Num }}）</span>
                  <span class="level-count" v-if="node.level === 2">（{{ node.data.Num }}）</span>
                </span>
              </span>
            </span>
          </el-tree>
        </div>
        <div class="rightBox" style="width: calc(100% - 240px)">
          <div class="box-content">
            <connsearch ref="connsearch" :formOptions="formOptions" @search="search" @reset="reset" />
            <div class="tabclick">
              <div class="tabitem" @click="handleClick()">
                <span><i :class="tab ? 'el-icon-arrow-up' : 'el-icon-arrow-down'"></i></span>
              </div>
            </div>
            <el-row>
              <el-tabs type="border-card" v-if="tab" style="margin-top: 16px" @tab-click="tabClick">
                <el-tab-pane label="日期趋势" lazy>
                  <el-col :xs="24" :sm="24" :lg="24">
                    <barchart :title="'显示日统计趋势'" :chartData="barchartData" @barclick="echartsClick" />
                  </el-col>
                </el-tab-pane>
                <el-tab-pane label="终端分析" lazy>
                  <el-row :gutter="20">
                    <el-col :xs="24" :sm="24" :lg="24">
                      <piechart :title="'终端统计分析'" :chartData="pie1Data" @pieclick="echartsClick" />
                    </el-col>
                  </el-row>
                </el-tab-pane>
              </el-tabs>
            </el-row>
            <!-- <barchart /> -->
            <el-col :xs="{ span: 24 }" :sm="{ span: 24 }" :md="{ span: 24 }" :lg="{ span: 24 }" :xl="{ span: 24 }"
              style="padding-right: 8px; margin: 16px 0">
              <!-- <span class="title">人工智能列表</span> -->
              <el-table stripe :data="tableData" style="width: 100%; margin-top: 15px">
                <el-table-column label="序号" width="60" type="index" :index="(index) => {
                  return index + 1 + (this.pageNum - 1) * this.pageSize;
                }
                  ">
                </el-table-column>
                <el-table-column label="使用时间" prop="TransTime" align="left" width="160px"
                  show-overflow-tooltip></el-table-column>
                <el-table-column label="使用终端" prop="Name" align="left" width="100px"
                  show-overflow-tooltip></el-table-column>
                <el-table-column label="使用版本" prop="Model" align="left" width="100px" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <span>{{ scope.row.Model }}
                      <!-- 答：{{ scope.row.Answer }} --></span>
                  </template>
                </el-table-column>
                <el-table-column label="会话标题" prop="ChatTitle" align="left" width="160px"
                  show-overflow-tooltip></el-table-column>
                <el-table-column label="请求方式" prop="Action" align="left" width="160px" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <span>{{ scope.row.Action === 1 ? "信息咨询" : scope.row.Action === 3 ? "图片创造" : "文案撰写" }}
                    </span>
                    <!-- 答：{{ scope.row.Answer }} -->
                  </template>
                </el-table-column>
                <el-table-column label="咨询问题" prop="Question" align="left" show-overflow-tooltip>
                  <template slot-scope="{ row }">
                    <span v-if="row.Action === 1 || row.Action === 3">{{ row.Question }} </span>
                    <!-- 答：{{ row.Answer }} -->
                    <div v-else m="4">
                      <span m="t-0 b-2" v-if="row.demand && row.demand.product">产品描述: {{ row.demand.product }};
                      </span>
                      <span m="t-0 b-2" v-if="row.demand && row.demand.company">公司描述: {{ row.demand.company }};
                      </span>
                      <span m="t-0 b-2" v-if="row.demand && row.demand.keyword">关键词: {{ row.demand.keyword }};
                      </span>
                      <span m="t-0 b-2" v-if="row.demand && row.demand.paragraphs">写作段落: {{ row.demand.paragraphs }};
                      </span>
                      <span m="t-0 b-2" v-if="row.demand && row.demand.modal">写作字数: {{ row.demand.modal }}; </span>
                      <span m="t-0 b-2" v-if="row.demand && row.demand.language">目标语言: {{ row.demand.language }};
                      </span>
                    </div>
                  </template>
                </el-table-column>
                <el-table-column label="操作" fixed="right" width="80px">
                  <template slot-scope="scope">
                    <el-button type="primary" size="mini" @click="handleEdit(scope.row)">详情</el-button>
                  </template>
                </el-table-column>
              </el-table>
              <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="pageNum"
                :page-size="pageSize" background layout="total, prev, pager, sizes, next, jumper" :total="total">
              </el-pagination>
            </el-col>
          </div>
        </div>
      </div>
    </el-row>
    <el-dialog title="详情" v-dragDialog :close-on-press-escape="false" :close-on-click-modal="false"
      :visible.sync="dialogVisible" width="calc(64% - 13px)">
      <span>
        <div style="display: flex; margin-bottom: 30px;">
          <div style="width: 120px; text-align: right;margin-right:10px;">咨询问题：</div>
          <el-input class="dynamic-textarea" type="textarea" v-model="question"></el-input>
        </div>
        <div style="display: flex">
          <div style="width: 120px; text-align: right;margin-right:10px;">AI回复：</div>
          <div v-show="Action === 3" class="AIanswer el-textarea__inner demo-image"
            style="display: flex; flex-wrap: wrap;width: 100%;">
            <div v-for="item in pictureList" :key="item.url" class="block" style="margin: 10px">
              <el-image style="width: 300px; height: 300px" :src="item.url" />
            </div>
          </div>
          <!-- <div  v-show="Action !== 3" class="AIanswer el-textarea__inner" v-html="answer"></div> -->
          <div style="position: relative; width: 100%" v-show="Action !== 3">
            <div class="chat-message-text" ref="code" style="height: 10%; overflow: auto" v-html="answer"></div>
          </div>
        </div>
      </span>
      <!--底部分割线 -->
      <el-divider class="lineToFooter"></el-divider>
      <span slot="footer" class="dialog-footer">
        <el-button type="primary" link icon="Tickets" @click="copyAnswer(answer)">复制AI回复</el-button>
        <el-button type="info" @click="dialogVisible = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
// 初始化 MarkdownIt
const md = new MarkdownIt({
  html: true,
  typographer: true,
  highlight: function (str, lang) {
    if (lang && Hljs.getLanguage(lang)) {
      try {
        let idname = `name${getuuid()}`;
        return (
          `<pre class="hljs"><div class="code-block-header"><span class="code-block-header__lang">${lang}</span><el-button class="code-block-header__copy" onClick='copy("${idname}")'>复制代码</el-button></div><code id='${idname}'>` +
          Hljs.highlight(lang, str, true).value +
          "</code></pre>"
        );
      } catch (__) { }
    }
    return "";
  }
});
import Cookies from "js-cookie";
import hljs from "highlight.js";
import "highlight.js/styles/github.css"; // 按需引入样式文件
import elDragDialog from "@/directive/el-maxsize-dialog/maximize"; // 新增的最大化指令
import { getNowDay, parseTime, getTreeData, ParamDictURLtype, Maintype } from "@/utils/index.js";
import { connrequest } from "@/api/firstPage.js";
import connsearch from "@/components/connSearch";
import barchart from "./components/barchart.vue";
import piechart from "./components/piechart.vue";
import "highlight.js/styles/monokai-sublime.css";
import Hljs from "highlight.js";
import MarkdownIt from "markdown-it/dist/markdown-it.js";
import { getuuid } from "@/utils/index.js";
export default {
  directives: { dragDialog: elDragDialog },
  components: { connsearch, barchart, piechart },
  data() {
    let that = this;
    return {
      activeName: "按日统计",
      tabTitle: "日期趋势",
      tableData: [],
      pageNum: 1,
      pageSize: 10,
      total: 0,
      tab: false,
      tab2: false,
      Action: "",
      dialogVisible: false,
      question: "",
      answer: "",
      pictureList: [],
      searchobj: {},
      answer1: '<pre><code class="">npm install qrcode</code></pre>',
      barchartData: { xAxis: [], series: [] },
      pie1Data: [],
      pie2Data: [],
      pie3Data: [],
      pie4Data: [],
      previewList: [],
      searchform: {},
      CustomerList: [],
      options: [], //用于提取终端用户
      md: md,
      defaultProps: {
        children: "children",
        label: "SubClass",
        Num: "Num"
      },
      formOptions: [
        {
          col: 10,
          label: "日期",
          prop: "timeRange",
          element: "el-date-picker",
          initValue: [],
          type: "",
          events: {
            input(val) {
              that.searchform.timeRange = val;
            }
          }
        },
        {
          col: 6,
          label: "终端用户",
          prop: "Name",
          element: "el-cascader",
          initValue: "",
          placeholder: "请选择终端用户",
          checkStrictly: false,
          options: [],
          events: {
            input(val) {
              that.searchform.Name = val;
            }
          }
        },
        {
          col: 8,
          label: "咨询问题",
          prop: "Descp",
          element: "el-input",
          placeholder: "请输入咨询问题关键字,支持模糊搜索",
          events: {
            input(val) {
              that.searchform.Descp = val;
            }
          }
        }
      ]
    };
  },
  //生命周期 - 创建完成（访问当前this实例）
  created() {
    this.pageSize = Cookies.get("DefaultPageLength") * 1;
    let endTime = new Date(new Date().setHours(0, 0, 0, 0));
    let startTime = endTime - Cookies.get("DefaultLogDays") * 1 * 3600 * 24 * 1000;
    let arr = [parseTime(startTime), ""];
    this.formOptions.map((item) => {
      if (item.label === "日期") {
        item.initValue = arr;
      }
    });
    this.$set(this.searchform, "timeRange", arr);
    this.getData();
    this.GetDepartment();
  },
  //生命周期 - 挂载完成（访问DOM元素）
  mounted() {
    // 初始绑定事件监听器
    this.$nextTick(() => {
      const dialogEl = this.$el; // 直接绑定到 $el（即 el 元素）
      if (dialogEl) {
        dialogEl.addEventListener("drag-resize", this.handleResize);
      }
      // 监听浏览器全屏事件
      document.addEventListener("fullscreenchange", this.handleFullscreenChange);
    });
  },
  watch: {
    dialogVisible(newVal) {
      if (!newVal) {
        // 对话框关闭时重置状态
        this.pictureList = [];
        const dialogEl = this.$el.querySelector(".el-dialog");
        if (dialogEl) {
          const questionWrapper = dialogEl.querySelector(".el-dialog__body .dynamic-textarea textarea");
          const answerWrapper = dialogEl.querySelector(".el-dialog__body .chat-message-text");
          if (questionWrapper) {
            questionWrapper.classList.remove("fullscreen");
          }
          if (answerWrapper) {
            answerWrapper.classList.remove("fullscreen");
          }
          // 强制调用 handleResize 重置高度
          this.handleResize();
        }
      }
    }
  },
  beforeDestroy() {
    // 清理事件监听器和定时器
    const dialogEl = this.$el;
    if (dialogEl) {
      dialogEl.removeEventListener("drag-resize", this.handleResize);
    }
    // 移除浏览器全屏事件监听器
    document.removeEventListener("fullscreenchange", this.handleFullscreenChange);
  },
  methods: {
    handleFullscreenChange() {
      // 浏览器全屏状态变化时，重新调用 handleResize
      if (this.dialogVisible) {
        this.handleResize();
      }
    },
    copyAnswer(data) {
      let elInput = document.createElement("textarea");
      elInput.value = data;
      document.body.appendChild(elInput);
      // 选择对象
      elInput.select();
      // 执行浏览器复制命令
      this.$message.success("复制成功");
      document.execCommand("Copy");
      elInput.remove();
    },
    getData() {
      this.GetShadowURLLog();
      switch (this.tabTitle) {
        case "日期趋势":
          this.GetChatGPTLogSumGroupByDate();
          break;
        default:
          this.GetChatGPTLogSumGroupByNameChat();
          break;
      }
    },
    echartsClick(val, title, id) {
      this.pageNum = 1;
      if (title === "显示日统计趋势") {
        this.searchobj = { StartTime: `${val} 00:00:00`, EndTime: `${val} 23:59:59` };
        this.GetShadowURLLog(this.searchobj);
      } else if (title === "终端统计分析") {
        this.searchobj = { Name: val };
        this.GetShadowURLLog(this.searchobj);
      }
    },
    tabClick(row) {
      this.tabTitle = row.label;
      switch (this.tabTitle) {
        case "显示日统计趋势":
          this.GetChatGPTLogSumGroupByDate();
          break;
        default:
          this.GetChatGPTLogSumGroupByNameChat();
          break;
      }
    },
    async handleNodeClick(item, node) {
      this.pageNum = 1;
      //如果点击部门，则按照部门请求数据
      if (node.level === 1) {
        this.searchobj = { Department: item.SubClass, Status: item.Status };
        this.GetShadowURLLog({ Department: item.SubClass, Status: item.Status });
      }
      if (node.level > 1) {
        let Name = node.level === 2 ? item.SubClass : node.level === 3 ? node.parent.data.SubClass : "";
        this.searchobj = { Name, Status: item.Status };
        this.GetShadowURLLog({ Name, Status: item.Status });
      }
    },
    // 获取部门和终端用户
    async GetDepartment() {
      const departments = await connrequest("GetDepartment");
      const employees = await connrequest("GetEmployee");
      departments.Data.map((item) => {
        item.SubClass = item.DepartmentName;
      });
      employees.Data.map((item) => {
        item.SubClass = item.Name;
        item.ParentID = item.DID;
      });
      // 提取 SubClass 并生成 options
      this.processEmployeeData(employees.Data);
      this.formOptions.map((item) => {
        if (item.label === "终端用户") {
          item.options = this.options;
        }
      });
    },
    //处理用户及部门分组
    processEmployeeData(employees) {
      // 创建一个对象，用于按 Department 分组
      const departmentMap = {};
      // 遍历数据，按 Department 分组
      employees.forEach((item) => {
        const department = item.Department;
        const name = item.Name;
        // 如果 Department 不存在，初始化一个空数组
        if (!departmentMap[department]) {
          departmentMap[department] = [];
        }
        // 将 Name 添加到对应的 Department 分组中
        departmentMap[department].push({
          SubClass: name
        });
      });
      // 将分组后的数据转换为 options 格式
      this.options = Object.keys(departmentMap).map((department) => {
        return {
          SubClass: department,
          children: departmentMap[department] // 对应的 Name 列表
        };
      });

      // 返回生成的 options
      return this.options;
    },
    convertArray(data) {
      const map = {};
      const result = [];
      data.forEach((item) => {
        if (!item.children) {
          item.children = [];
        }
        map[item.ID] = item;
      });
      data.forEach((item) => {
        if (item.ParentID !== 0) {
          const parent = map[item.ParentID];
          parent.children.push(item);
        } else {
          result.push(item);
        }
      });
      return result;
    },
    addFourthLevel(departments) {
      // 创建一个新的数组来存储处理结果
      const result = departments.map((department) => {
        // 复制原始对象，并添加 children 属性
        const departmentCopy = { ...department };
        if (departmentCopy.children.length > 0) {
          departmentCopy.children = departmentCopy.children.map((user) => {
            // 复制原始对象，并添加 children 属性
            const userCopy = { ...user };
            userCopy.children = [
              { SubClass: "信息咨询", Status: 1 },
              { SubClass: "文案撰写", Status: 2 },
              { SubClass: "图片创造", Status: 3 }
            ];
            return userCopy;
          });
        }
        return departmentCopy;
      });
      return result;
    },
    // 获取事件日期统计
    async GetChatGPTLogSumGroupByDate() {
      let xAxis = [];
      let series = [];
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || "",
          EndTime: this.searchform.timeRange?.[1] || "",
          Name: this.searchform?.Name ? this.searchform?.Name[this.searchform.Name.length - 1] : "",
          Descp: this.searchform.Descp || "",
          SumCount: 10
        }
      };
      const res = await connrequest("GetChatGPTLogSumGroupByDate", data);
      res.Data = res.Data || [];
      res.Data.map((item) => {
        xAxis.push(item.Name);
        series.push(item.Count);
      });
      this.barchartData = { xAxis, series };
    },
    // 获取审计用户统计
    async GetChatGPTLogSumGroupByNameChat() {
      let arr = [];
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || "",
          EndTime: this.searchform.timeRange?.[1] || "",
          TransDate: "",
          Name: this.searchform?.Name ? this.searchform?.Name[this.searchform.Name.length - 1] : "",
          Descp: this.searchform.Descp || "",
          SumCount: 10
        }
      };
      const res = await connrequest("GetChatGPTLogSumGroupByName", data);
      res.Data = res.Data || [];
      res.Data.map((item) => {
        arr.push({ name: item.Name, value: item.Count });
      });
      this.pie1Data = arr;
    },
    // 获取人工智能列表
    async GetShadowURLLog(searchobj = {}) {
      const data = {
        Paging: {
          QueryPageNo: this.pageNum,
          QueryPageLength: this.pageSize
        },
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || "",
          EndTime: this.searchform.timeRange?.[1] || "",
          TransDate: "",
          Name: this.searchform?.Name ? this.searchform?.Name[this.searchform.Name.length - 1] : "",
          Descp: this.searchform.Descp || "",
          UserRole: "admin",
          ...searchobj
        }
      };
      const res = await connrequest("GetChatGPTLog", data);
      res.Data = res.Data || [];
      res.Data.map((item) => {
        item.TransTime = parseTime(item.TransTime, "{y}-{m}-{d} {h}:{i}:{s}");
        if (item.Action === 2) {
          item.demand = this.extractContent(item.Question);
          if (item.Question !== "" && JSON.parse(item.Question).messages) {
            item.Question = JSON.parse(item.Question).messages[1]?.content;
          }
        }
      });
      this.tableData = res.Data;
      this.total = res.Paging.TotalCount;
      this.GetChatGPTLogSumGroupByName();
    },
    handleSizeChange(val) {
      this.pageNum = 1;
      this.pageSize = val;
      this.GetShadowURLLog(this.searchobj);
    },
    handleCurrentChange(pageNum) {
      this.pageNum = pageNum;
      this.GetShadowURLLog(this.searchobj);
    },
    search(val) {
      this.pageNum = 1;
      this.searchform = { ...val };
      if (this.searchform.timeRange) {
        this.searchobj = {
          StartTime: this.searchform?.timeRange[0] || "",
          EndTime: this.searchform?.timeRange[1] || ""
        };
      }
      this.getData();
      this.GetChatGPTLogSumGroupByName();
    },
    async GetChatGPTLogSumGroupByName(searchobj = {}) {
      const data = {
        Filter: {
          StartTime: this.searchform.timeRange?.[0] || "",
          EndTime: this.searchform.timeRange?.[1] || "",
          TransDate: "",
          Name: this.searchform?.Name ? this.searchform?.Name[this.searchform.Name.length - 1] : "",
          Descp: this.searchform.Descp || "",
          ...searchobj
        }
      };
      const res = await connrequest("GetChatGPTLogSumGroupByName", data);
      this.CustomerList = this.transformData(res.Data);
    },
    transformData(data) {
      data = data || [];
      const result = data.reduce((prev, curr) => {
        const departmentExist = prev.find((item) => item.SubClass === curr.Department);
        const employee = {
          SubClass: curr.Name,
          Num: curr.Count,
          id: "",
          children: [
            {
              SubClass: "信息咨询",
              id: "",
              Num: curr.Action1,
              Status: 1
            },
            {
              SubClass: "文案撰写",
              id: "",
              Num: curr.Action2,
              Status: 2
            },
            {
              SubClass: "图片创造",
              id: "",
              Num: curr.Action3,
              Status: 3
            }
          ]
        };
        if (departmentExist) {
          departmentExist.children.push(employee);
        } else {
          prev.push({
            SubClass: curr.Department,
            Num: "",
            id: "",
            children: [employee]
          });
        }
        return prev;
      }, []);
      return result;
    },
    reset() {
      let endTime = new Date(new Date().setHours(0, 0, 0, 0));
      let startTime = endTime - Cookies.get("DefaultLogDays") * 1 * 3600 * 24 * 1000;
      let arr = [parseTime(startTime), ""];
      this.pageNum = 1;
      this.formOptions = this.formOptions.map((item) => {
        if (item.label === "域名分类" || item.label === "日期") {
          item.initValue = arr;
        } else if (item.label === "统计排名") {
          item.initValue = 10;
        } else if (item.label === "审计结果") {
          item.initValue = 0;
        } else {
          item.initValue = "";
        }
        return item;
      });
      this.searchform = {};
      this.searchobj = {};
      this.$set(this.searchform, "timeRange", arr);
      this.$refs.connsearch.addInitValue();
      this.getData();
    },
    handleClick() {
      this.tab = !this.tab;
    },
    // 处理调整大小事件，更新行数
    handleResize() {
      const dialogEl = this.$el.querySelector(".el-dialog");
      if (dialogEl) {
        let isFullscreen = dialogEl.fullscreen;
        if (typeof isFullscreen === "undefined") {
          const width = dialogEl.style.width;
          const height = dialogEl.style.height;
          isFullscreen = width === "100vw" && height === "100vh";
        }
        const dialogBody = dialogEl.querySelector(".el-dialog__body");
        if (!dialogBody) {
          return;
        }
        const questionTextarea = dialogEl.querySelector(".el-dialog__body .dynamic-textarea textarea");
        const answerTextarea = dialogEl.querySelector(".el-dialog__body .chat-message-text");
        const dialogHeader = dialogEl.querySelector(".el-dialog__header");
        const dialogFooter = dialogEl.querySelector(".el-dialog__footer");
        if (!questionTextarea || !answerTextarea) {
          return;
        }
        setTimeout(() => {
          const dialogBodyHeight = dialogEl.style.height - dialogHeader.style.height - dialogFooter.style.height;
          // 动态设置 el-dialog__body 的高度
          dialogBody.style.height = isFullscreen ? dialogBodyHeight : "auto";
          if (isFullscreen) {
            dialogBody.classList.add("fullscreen");
          } else {
            dialogBody.classList.remove("fullscreen");
          }
          if (questionTextarea) {
            questionTextarea.style.height = isFullscreen ? "calc(22vh - 37px)" : "calc(14vh - 15px)";
            const questionWrapper = dialogEl.querySelector(".el-dialog__body .dynamic-textarea:nth-of-type(1)");
            if (questionWrapper) {
              if (isFullscreen) {
                questionWrapper.classList.add("fullscreen");
              } else {
                questionWrapper.classList.remove("fullscreen");
              }
            }
          }
          if (answerTextarea) {
            answerTextarea.style.height = isFullscreen ? "calc(60vh - 10px)" : "calc(45vh - 20px)";
            const answerWrapper = dialogEl.querySelector(".el-dialog__body .dynamic-textarea:nth-of-type(2)");
            if (answerWrapper) {
              if (isFullscreen) {
                answerWrapper.classList.add("fullscreen");
              } else {
                answerWrapper.classList.remove("fullscreen");
              }
            }
          }
          this.$forceUpdate();
        }, 0);
      }
    },
    handleEdit(row) {
      if (row.Action === 3) {
        try {
          // 使用环境变量或动态获取基础 URL
          const baseUrl = process.env.VUE_APP_API_URL || window.location.origin;
          const previewList = JSON.parse(row.Answer || '[]'); // 防止 row.Answer 为空
          this.pictureList = previewList
            .filter(item => item && typeof item.url === 'string') // 过滤无效项
            .map(item => ({
              url: `${baseUrl}${item.url.startsWith('/') ? '' : '/'}${item.url}` // 规范化 URL
            }));
        } catch (error) {
          this.pictureList = []; // 错误时设置为空数组
        }
      }

      this.Action = row.Action;
      this.question = row.Action === 2 ? this.answerForm(this.extractContent(row.Question)) : row.Question;
      let Answer = "";
      if (row.Action === 2) {
        if (row.Answer !== "" && JSON.parse(row.Answer).choices) {
          Answer = JSON.parse(row.Answer).choices[0].message.content;
        }
      }
      this.answer = row.Action === 2 ? this.md.render(Answer) : this.md.render(row.Answer);
      this.dialogVisible = true;
      this.$nextTick(() => {
        const code = this.$refs.code;
        if (code) {
          hljs.highlightAll();
          // hljs.highlightBlock(code);
        }

        // 延迟绑定事件监听器，确保 DOM 已渲染
        setTimeout(() => {
          const dialogEl = this.$el; // 直接绑定到 $el
          if (dialogEl) {
            dialogEl.removeEventListener("drag-resize", this.handleResize);
            dialogEl.addEventListener("drag-resize", this.handleResize);
            this.handleResize();
          }
        }, 100);
      });
    },
    extractContent(paragraph) {
      const productRegex = /(?<=product description: {)[^{}]+(?=})/;
      const keywordRegex = /(?<=Combine keywords: {)[^{}]+(?=})/;
      const companyRegex = /(?<=Combining company description: {)[^{}]+(?=})/;
      const paragraphsRegex = /(?<=in )[0-9]+(?= paragraphs\.)/;
      const modalRegex = /(?<=approximately)[^ ]+(?= words of written content)/;
      const wordCountRegex = /\d+(?= words of)/;
      const languageRegex = /(?<=written content in )\w+/;
      const product = paragraph.match(productRegex) ? paragraph.match(productRegex)[0] : "";
      const keyword = paragraph.match(keywordRegex) ? paragraph.match(keywordRegex)[0] : "";
      const company = paragraph.match(companyRegex) ? paragraph.match(companyRegex)[0] : "";
      const paragraphs = paragraph.match(paragraphsRegex) ? parseInt(paragraph.match(paragraphsRegex)[0]) : "";
      const modal = paragraph.match(modalRegex) ? paragraph.match(modalRegex)[0] : "";
      const wordCount = paragraph.match(wordCountRegex) ? parseInt(paragraph.match(wordCountRegex)[0]) : "";
      const language = paragraph.match(languageRegex) ? paragraph.match(languageRegex)[0] : "";
      return {
        product,
        keyword,
        company,
        paragraphs,
        modal,
        wordCount,
        language
      };
    },
    answerForm(value) {
      const product = value;
      const company = product.company ? `公司描述: ${product.company}\n` : "";
      const keyword = product.keyword ? `关键词: ${product.keyword}\n` : "";
      const paragraphs = product.paragraphs ? `写作段落: ${product.paragraphs}\n` : "";
      // const modal = product.modal ? `写作语气: ${product.modal}\n` : '';
      const wordCount = product.wordCount ? `字数: ${product.wordCount}\n` : "";
      const language = product.language ? `目标语言: ${product.language}\n` : "";
      return `产品描述：${product.product}\n${company}${keyword}${paragraphs}${wordCount}${language}`;
    }
  }
};
</script>
<style lang="scss" scoped>
@import "~@/styles/variables.scss";
@import "./components/css/conncss.scss";

.AIanswer {
  width: calc(100% - 70px);
  height: 400px;
  overflow: auto;
}

.chat-message-text {
  width: 100%;
  overflow-y: auto;
  align-self: flex-start;
  border-radius: 5px;
  padding: 0 10px;
  background-color: #f4f6f8;
  word-wrap: break-word;
  ::v-deep a, a:focus, a:hover{
    color: #409eff;
    border-bottom: 1px solid #409eff
  }
}



.demo-image {
  display: flex;

  .block {
    width: 300px;
  }
}

/* 设置垂直滚动条（如果需要水平滚动条，请添加::-webkit-scrollbar-horizontal选择器） */
::-webkit-scrollbar {
  width: 3px;
  /* 滚动条宽度 */
}

/* 滚动条轨道部分（即背景） */
::-webkit-scrollbar-track {
  background-color: #fff;
  /* 背景颜色 */
}

/* 滚动条上下两端的按钮 */
::-webkit-scrollbar-button {
  display: none;
  /* 隐藏按钮 */
}

/* 滚动条滑块部分（即滑块本身） */
::-webkit-scrollbar-thumb {
  background-color: #ccc;
  /* 滑块颜色 */
}

.copyButton {
  position: absolute;
  bottom: 10px;
  right: 20px;
  z-index: 100000000;
  color: #409eff;
}

.lefttree {
  border: 1px solid #ebeef5;
  padding: 10px;
  position: relative;
  overflow-y: auto;

  .tabclick {
    transform: rotate(-90deg);
    position: absolute;
    top: calc((100vh - 300px) / 2);
    left: -55px;
    margin-top: 20px;
  }

  ::v-deep .el-tree {
    color: #676c70;
    background-color: #ffffff;

    .tree-text {
      font-size: 14px;
      display: inline-block;
      width: 130px;
      text-align: justify;
      white-space: nowrap;
      /* 禁止换行 */
      overflow: hidden;
      /* 溢出隐藏 */
      text-overflow: ellipsis;
      /* 超出部分用省略号表示 */
    }

    // .tree-text:before {
    //   content: "";
    //   display: inline-block;
    //   width: 100%;
    //   height: 0;
    // }

    // .tree-text:after {
    //   content: "...";
    //   display: inline-block;
    //   width: 1em;
    //   margin-left: -1em;
    // }
  }

  ::v-deep.el-tree-node__content {
    &:hover {
      background-color: #eee;
    }
  }

  ::v-deep .el-tree-node.is-current>.el-tree-node__content {
    color: #459ffc !important;
    background-color: #f7f7f7 !important;
  }

  // ::v-deep .el-tree-node__expand-icon{
  //   position :absolute;
  //   left: 2%;
  // }
  ::v-deep .el-tree-node__label {
    padding-left: 15px;
  }
}

.rightBox {
  margin: 20px;
}

.night {
  .chat-message-text {
    background-color: #3e4252;
  }

  .lefttree {
    background: #303445;
    border: 1px solid #303445;

    ::v-deep .el-tree {
      color: #d0d0d3;
    }
  }

  .container {
    background: #2a2d3c;
  }

  .rightBox {
    margin: 0px;
    background: #303445;
    margin-left: 20px;
  }

  .box-content {
    margin: 20px;
  }
}

::v-deep .el-icon-full-screen:before,
::v-deep .el-icon-crop:before {
  color: #fff !important;
  margin-right: 10px !important;
}
</style>
